package com.atguigu.admin.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.atguigu.admin.model.dto.RegisterDto;
import com.atguigu.admin.model.entity.SysUser;
import com.atguigu.admin.model.menu.MinIOEnum;
import com.atguigu.admin.model.vo.LoginVo;
import com.atguigu.admin.service.SysUserService;
import com.atguigu.admin.utils.DataUtil;
import com.atguigu.common.result.Result;
import com.atguigu.common.result.ResultCodeEnum;
import com.atguigu.common.utils.JwtUtils;
import com.atguigu.core.config.MinioUtil;
import com.atguigu.core.execption.GuiguException;
import com.atguigu.system.model.entity.dto.UpPasswordDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.atguigu.security.utils.SecurityUtil.matchesPassword;

/**
 * <p>
 * 后台登录登出
 * </p>
 */
@Api(tags = "登录管理")
@RestController
@RequestMapping("/admin")
@CrossOrigin
@Slf4j
public class IndexController {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysUserService sysUserService;


    @Value("${minioTemp.endpoint}")
    private String endpoint;

    @Value("${minioTemp.bucketName}")
    private String bucketName;

    private final MinioUtil minioUtil;

    public IndexController(MinioUtil minioUtil) {
        this.minioUtil = minioUtil;
    }

    /**
     * 登录
     *
     * @return
     */
    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo,HttpServletRequest request) {

        SysUser sysUser = sysUserService.getUserInfoByUserName(loginVo.getUsername());
        if (null == sysUser) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        if (!passwordEncoder.matches(loginVo.getPassword(), sysUser.getPassword())) {
            throw new GuiguException(ResultCodeEnum.PASSWORD_ERROR);
        }
        if (sysUser.getStatus() == 0) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("token", JwtUtils.createToken(String.valueOf(sysUser.getId()), sysUser.getUsername()));
        return Result.ok(map);
    }

    @ApiOperation(value = "获取用户信息-权限等信息")
    @GetMapping("/info")
    public Result info(HttpServletRequest request) {
        String username = JwtUtils.getUsername(request.getHeader("token"));
        Map<String, Object> map = sysUserService.getUserInfo(username);
        return Result.ok(map);
    }

    @ApiOperation(value = "获取用户最基本信息")
    @GetMapping("/getBaseInfo")
    public Result getBaseInfo(HttpServletRequest request) {
        String username = JwtUtils.getUsername(request.getHeader("token"));
        Map<String, Object> map = sysUserService.getBaseUserInfo(username);
        return Result.ok(map);
    }


    @ApiOperation(value = "获取验证码")
    @GetMapping("/captch/*")
    public void info(HttpServletResponse response, HttpSession session, HttpServletRequest request) {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100,35,4,25);
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        try{
            lineCaptcha.write(response.getOutputStream());
            String code = lineCaptcha.getCode();
            request.getSession().setAttribute("captcha",code);
            log.info("验证码：{}",code);
            response.getOutputStream().close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }


    @ApiOperation(value = "注册接口")
    @PostMapping("/register")
    public Result info(HttpServletRequest request,@RequestBody RegisterDto registerDto) {
        Object captcha = request.getSession().getAttribute("captcha");
        System.out.println(captcha);
        if (!registerDto.getCaptcha().equals(captcha.toString())){
            return  Result.fail().message("验证码输入错误！");
        }
        if (sysUserService.getUserInfoByUserName(registerDto.getUsername()) != null){
            return  Result.fail().message("用户名已存在！");
        }
        if (!registerDto.getPassword().equals(registerDto.getCheckPass())){
            return  Result.fail().message("请校验您输入的两次密码是否相同！");
        }
        Boolean flag = sysUserService.register(registerDto);
        if (flag){
            return Result.ok();
        }else{
            return Result.fail();
        }
    }

    /**
     * 修改
     * @param
     * @return
     */
    @ApiOperation(value = "修改基本信息接口")
    @PutMapping("/upUserInfo")
    public Result upPassWord(@RequestBody SysUser sysUser,HttpServletRequest request) {
        String userName = JwtUtils.getUsername(request.getHeader("token"));
        if (userName.equals(sysUser.getUsername())){
            String headUrl = sysUser.getHeadUrl();
            int lastSlashIndex = headUrl.lastIndexOf("/");
            String pathPart = headUrl.substring(lastSlashIndex + 1);
            sysUser.setHeadUrl(pathPart);
            boolean state = sysUserService.updateById(sysUser);
            if (state){
                return Result.ok("用户信息修改成功！");
            }else {
                return Result.fail("用户信息修改失败！");
            }
        }else {
            return Result.fail("您没有权限修改他人信息！");
        }
    }

    @ApiOperation(value = "修改基本信息接口")
    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestBody UpPasswordDto upPasswordDto, HttpServletRequest request) {
        Object captcha = request.getSession().getAttribute("captcha");
        if (DataUtil.isEmpty(captcha)){
            return  Result.fail().message("请重新获取验证码！");
        }
        if (!upPasswordDto.getCaptcha().equals(captcha.toString())){
            return  Result.fail().message("验证码输入错误！");
        }
        String userName = JwtUtils.getUsername(request.getHeader("token"));
        SysUser sysUser = sysUserService.getUserInfoByUserName(userName);
        if (upPasswordDto.getOldPassword().equals(upPasswordDto.getPassword())){
            return  Result.fail().message("您输入的旧密码与新密码相同！");
        }
        if (userName.equals(sysUser.getUsername())){
            boolean state = sysUserService.resetPassword(upPasswordDto,userName);
            if (state){
                return Result.ok().message("密码修改成功！");
            }else {
                return Result.fail().message("密码修改失败！");
            }
        }else {
            return Result.fail().message("密码修改失败:权限异常！");
        }
    }


    @ApiOperation(value = "用户上传头像并返回头像url接口")
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {

        //具体文件，存储桶名称，存储路径
        String objectName = minioUtil.upload(file, MinIOEnum.USER_BUCKET.getName(), MinIOEnum.USER_BUCKET_IMAGES.getName());
        if (null != objectName) {
            return Result.ok(endpoint + "/" + bucketName + "/" + objectName);
        }
        return Result.fail("文件上传错误");
    }


    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    public Result logout() {
        return Result.ok();
    }
}
